package com.gx.smart.construction.ui.open.viewmodel

import android.app.Application
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.casic.gx.grpc.common.ComResp
import com.casic.gx.grpc.qrcodepass.QRCodePassResp
import com.casic.gx.grpc.qrcodepass.UserInfo
import com.gx.smart.common.util.AppConfig
import com.gx.smart.construction.ui.common.viewmodel.CommonViewModel
import com.gx.smart.lib.http.api.OpenDoorService
import com.gx.smart.lib.http.api.asynctask.CallBack
import com.orhanobut.logger.Logger
import java.util.*

/**
 * @author xiaosy
 * @create 2020/8/7
 * @Describe
 */
class OpenDoorViewModel(application: Application) : CommonViewModel(application) {
    private val device = MutableLiveData<Device>()
    fun getQrCodePass(roomId: Long): LiveData<Device> {
        val isVisitor: Int = 2 // 是否访客 1访客 2业主
        val isPass: Int = 1
        val time: Long = Calendar.getInstance().timeInMillis / 1000
        val beginTime: Int = time.toInt()
        val endTime: Int = beginTime + 60
        val userInfo = UserInfo.newBuilder()
            .setUserId(0)
            .setGender(1)
            .setCertType(0)
            .setBeginTime(beginTime)
            .setEndTime(endTime)
            .setRoomId(roomId)
            .build()
        val sysTenantNo = SPUtils.getInstance().getInt(AppConfig.SYS_TENANT_NO, 0)
        OpenDoorService.getInstance().getQrCodePass(sysTenantNo, isVisitor,
            isPass, userInfo,
            object : CallBack<QRCodePassResp>() {
                override fun callBack(result: QRCodePassResp?) {
                    if (result == null) {
                        error.value = true
                        ToastUtils.showLong("获取二维码超时")
                        return
                    }
                    if (result.comResp.code == 100) {
                        val data = Device()
                        data.qrCode = result.qrCode
                        data.deviceType =
                            result.deviceType //设备类型    5002：立方门禁系统，  5003：ABB，   5004：一码通
                        device.setValue(data)
                    } else {
                        with(error) { setValue(true) }
                        //提示error
                        val resp: ComResp = result.comResp
                        Logger.d("msg:${resp.msg}")
                        Logger.d("err:${resp.err}")
                        Logger.d("tip:${resp.tip}")
                        ToastUtils.showLong(result.comResp.err)
                    }
                }
            })
        return device
    }
}